package com.hotel.utils;




import com.hotel.entity.Category;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 类别树构建器
 *
 * @author Li
 * @date 2022/06/01
 */
public class CategoryTreeBuilder {

    /**
     * 构建多级菜单树
     * @param rootCategory
     * @return
     */
    public static List<Category> build(List<Category> rootCategory){
        //直接在这里查是完全没问题的
        // 存储最终的一个树形菜单
        List<Category> CategoryList = new ArrayList<>();
        // 先要查询父级菜单
        for (Category category : rootCategory) {
            if(category.getParentId()==0){
                //添加到父级菜单
                CategoryList.add(category);
            }
        }
        /* 根据Menu类的order排序 */
       Collections.sort(CategoryList,Category.order());

        //需要给父级菜单设置子菜单
        for (Category category : CategoryList) {
            category.setChildCategory(getChild(category.getId(), rootCategory));
        }
        return CategoryList;
    }

    private static List<Category> getChild(Long id, List<Category> rootCategory) {
        // 子菜单
        List<Category> childList = new ArrayList<>();
        //这里是二级菜单
        for (Category category: rootCategory
        ) {
            //1.不是0  2.父级id必须要和传过来的父级id相等
            if(!category.getParentId().equals("0")&&category.getParentId().equals(id)){
                childList.add(category);
            }
        }
        //对子集菜单进行排序
        Collections.sort(childList,Category.order());
        //三级以及三级以上的菜单使用递归实现
        for (Category category : childList
        ) {
            category.setChildCategory(getChild(category.getId(), rootCategory));
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
